﻿package  com.devilcat.ws{
	import com.devilcat.ws.Basicws;
	import com.worlize.websocket.*;
	import com.devilcat.dt.Gamedt;
	import flash.utils.clearInterval;
	import flash.utils.setInterval;
	
	public class PVPws extends Basicws{
		public var itv:uint;
		public var askid:uint;
		public function PVPws() {
			super("iw-protocol");
		}
		override function handleWebSocketOpen(event:WebSocketEvent):void
		{
		}
		public function waitRespon(){
			var pack:Object = new Object();
			pack.uid=Gamedt.Player.uid;
			pack.askid=askid;
			pack.action="waitrespon";
			var myJson:String = JSONString(pack);
			websocket.sendUTF(myJson);		
			
		}
		public function sendRequest(_askid:uint){
			var pack:Object = new Object();
			askid=_askid;
			pack.uid=Gamedt.Player.uid;
			pack.askid=askid;
			pack.action="sendrequest";
			var myJson:String = JSONString(pack);
			websocket.sendUTF(myJson);			
		}
		public function clearItv(){
			clearInterval(itv);			
		}
		override function handleWebSocketMessage(event:WebSocketEvent):void
		{
			if (event.message.type === WebSocketMessage.TYPE_UTF8)
			{	
				var dumpo:Object = JSONObject(event.message.utf8Data);
					trace("PVPWS "+event.message.utf8Data);
					Gamedt.MainUI.GameMenu.PVPPanel.PVPLog.text=dumpo.error;
				if(dumpo.error=="pass"){
					clearInterval(itv);
					Gamedt.pvp=true;
					Gamedt.MainUI.startPVP(askid);
					//Gamedt.MainUI.errorToken();
				}
				if(dumpo.error=="ok"){
					Gamedt.pvp=true;
					itv = setInterval(waitRespon,200);
					//Gamedt.MainUI.errorToken();
				}
				if(dumpo.error=="false"){
					Gamedt.pvp=true;
					clearInterval(itv);
					Gamedt.MainUI.clearPVP();
					//Khong the goi yeu cau
					//Gamedt.MainUI.errorToken();
				}
			}
		}

	}
	
}
